package com.yuexunit.mobilenurse.module.PatientDetail.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Cost.ui.Act_Cost;
import com.yuexunit.mobilenurse.module.DocAdvice.ui.Act_DocAdvice;
import com.yuexunit.mobilenurse.module.HealthArticles.ui.Act_Article;
import com.yuexunit.mobilenurse.module.Inspect.ui.Act_Inspect;
import com.yuexunit.mobilenurse.module.PatientDetail.bean.Patient_Patinfo;
import com.yuexunit.mobilenurse.module.PatientDetail.model.impl.PatientDetailModel;
import com.yuexunit.mobilenurse.module.PatientDetail.presenter.IPatientDetailPresenter;
import com.yuexunit.mobilenurse.module.PatientDetail.presenter.impl.PatientDetailPresenter;
import com.yuexunit.mobilenurse.module.PatientDetail.ui.view.IPatientDetailView;
import com.yuexunit.mobilenurse.module.Test.ui.Act_Test;
import com.yuexunit.mobilenurse.widget.Dialog_BloodPass;
import com.yuexunit.mobilenurse.widget.Dialog_BloodRepeat;
import com.yuexunit.mobilenurse.widget.Dialog_BloodUnpass;
import com.yuexunit.mobilenurse.widget.Dialog_Fail;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by work-jx on 2016/4/22.
 */
public class Act_PatientDetail_Advantech extends KJActivity implements IPatientDetailView {
    //病人基本信息组件
    @Bind(R.id.patient_pic)
    public ImageView patient_pic;
    @Bind(R.id.patient_name)
    public TextView patient_name;
    @Bind(R.id.patient_grade)
    public TextView patient_grade;
    @Bind(R.id.patient_age)
    public TextView patient_age;
    @Bind(R.id.patient_sex)
    public TextView patient_sex;
    @Bind(R.id.patient_doc)
    public TextView patient_doc;
    @Bind(R.id.patient_bed)
    public TextView patient_bed;
    @Bind(R.id.patient_date)
    public TextView patient_date;
    @Bind(R.id.patient_hospital)
    public TextView patient_hospital;
    @Bind(R.id.patient_lesion)
    public TextView patient_lesion;
    @Bind(R.id.patient_diagnose)
    public TextView patient_diagnose;
    //当前病人住院号
    private String Visitno;
    //日期显示格式
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",java.util.Locale.getDefault());
    private IPatientDetailPresenter presenter;
    private LoadingDialog dialog;

    //扫描号码
    String code;

    //采血成功计时
    Handler handler_blood;
    Timer time;
    TimerTask timetask;
    int countTime = 3;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_patientdetail);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        dialog = new LoadingDialog(aty);
        presenter = new PatientDetailPresenter(new PatientDetailModel(), this);
        Visitno = PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO);
    }

    @Override
    public void initWidget() {
        super.initWidget();
        presenter.showPatientDetail(Visitno);
    }

    @OnClick({R.id.find_plugin_1,R.id.find_plugin_2,R.id.find_plugin_3,R.id.find_plugin_4,
            R.id.find_plugin_5,R.id.find_plugin_6,R.id.titlebar_img_back,R.id.find_plugin_7})
    public void PatientFunction(View view) {
        switch (view.getId()) {
            case R.id.find_plugin_1:
                Bundle bundle = new Bundle();
                bundle.putString("source",AppConfig.CLICK);
                showActivity(aty, Act_DocAdvice.class, bundle);
                break;
            case R.id.find_plugin_2:
                showActivity(aty, Act_Test.class);
                break;
            case R.id.find_plugin_3:
                showActivity(aty, Act_Inspect.class);
                break;
            case R.id.find_plugin_4:
//                showActivity(aty, Act_Signs_Input.class);
                break;
            case R.id.find_plugin_5:
                showActivity(aty, Act_Cost.class);
                break;
            case R.id.find_plugin_6:
                showActivity(aty, Act_Article.class);
                break;
            case R.id.titlebar_img_back:
                finish();
            case R.id.find_plugin_7:
//                showActivity(aty, Act_Signs_Query.class);
                break;
        }
    }

    @Override
    public void showPatientDetail(Patient_Patinfo currentPatient) {
        //判断当前向服务器发送的病人住院号请求与服务器发回来的病人是否一致
        if (Visitno != null) {
            if (!Visitno.equals(currentPatient.getVisit_no())) {
                ViewInject.toast("服务器返回数据错误");
                return;
            }
        }

        //其中保存当前病人的床号到当前病人信息中
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_BEDCODE, currentPatient.getBedcode());
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_NAME, currentPatient.getName());
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_PRE, currentPatient.getPrepay() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_TOTAL, currentPatient.getTotalfee() + "");
        PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_DATE, formatter.format(currentPatient.getAdmissiondate()) + "");

        if ("M".equals(currentPatient.getSex()) && currentPatient.getAge() > AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_male_circle);
        } else if ("M".equals(currentPatient.getSex()) && currentPatient.getAge() < AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_boy_circle);
        } else if ("F".equals(currentPatient.getSex()) && currentPatient.getAge() > AppConfig.AGE_LIMIT) {
            patient_pic.setImageResource(R.drawable.pic_female_circle);
        } else {
            patient_pic.setImageResource(R.drawable.pic_girl_circle);
        }

        patient_name.setText(currentPatient.getName());
        patient_grade.setText(currentPatient.getGradename() + "级");
        patient_age.setText(currentPatient.getAge() + "");
        if ("M".equals(currentPatient.getSex())) {
            patient_sex.setText("男");
        } else if ("F".equals(currentPatient.getSex())) {
            patient_sex.setText("女");
        } else {
            patient_sex.setText("未知");
        }
        patient_doc.setText(currentPatient.getMdoctorname());
        patient_bed.setText(currentPatient.getBedcode());
        patient_hospital.setText(currentPatient.getVisit_no());
        patient_lesion.setText(currentPatient.getWardname());
        patient_diagnose.setText(currentPatient.getDiagnosis());
        patient_date.setText(formatter.format(currentPatient.getAdmissiondate()));
    }


    @Override
    public void loadingDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
                break;

            case AppConfig.DISMISS_DIALOG:
                dialog.dismiss();
                break;

        }
    }

    @Override
    public void NoPatientDialog() {
        Dialog_Fail.Builder builder_fail = new Dialog_Fail.Builder(aty);
        builder_fail.setMessage("未查到该病人信息");
        builder_fail.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });

        builder_fail.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
        builder_fail.create().show();
    }

    @Override
    public void bloodDialog(int status) {
        switch (status) {
            case AppConfig.BLOOD_DIALOG_REPEAT:
                display_bloodrepeat();
                break;
            case AppConfig.BLOOD_DIALOG_UNPASS:
                display_bloodunpass();
                break;
            case AppConfig.BLOOD_DIALOG_PASS:
                display_bloodpass();
                break;
        }
    }

    private void display_bloodrepeat() {
        final Dialog_BloodRepeat.Builder dialog_repeat = new Dialog_BloodRepeat.Builder(aty);
        dialog_repeat.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
        dialog_repeat.create().show();
    }

    private void display_bloodunpass() {
        final Dialog_BloodUnpass.Builder dialog_unpass = new Dialog_BloodUnpass.Builder(aty);
        dialog_unpass.setPositiveButton("确认",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                });
        dialog_unpass.create().show();
    }

    private void display_bloodpass() {
        final Dialog_BloodPass.Builder dialog_pass = new Dialog_BloodPass.Builder(aty);
        dialog_pass.create().show();
        handler_blood = new Handler() {
            public void handleMessage(Message msg) {
                if (msg.what > 0) {
                    Log.v("time", msg.what + "");
                } else {
                    countTime = 3;
                    if (time != null) {
                        time.cancel();
                        time = null;
                    }

                    if (timetask != null) {
                        timetask.cancel();
                        timetask = null;
                    }
                    dialog_pass.dismiss();
                }
                super.handleMessage(msg);
            }

        };

        time = new Timer(true);
        timetask = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                handler_blood.sendMessage(msg);

            }

        };
        time.schedule(timetask, 0, 1000);
    }

    @Override
    public void onResume(){
        super.onResume();
        Intent sendIntent = new Intent("df.scanservice.toapp");
        sendBroadcast(sendIntent);

        IntentFilter ItFilter = new IntentFilter();
        ItFilter.addAction("df.scanservice.result");
        this.registerReceiver(myReceiver, ItFilter);
    }

    @Override
    public void onStop(){
        super.onStop();
        try {
            this.unregisterReceiver(myReceiver);
//            Intent sendIntent = new Intent("df.scanservice.cancelapp");
//            sendBroadcast(sendIntent);
        } catch (IllegalArgumentException e) {

        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        try {
            this.unregisterReceiver(myReceiver);
//            Intent sendIntent = new Intent("df.scanservice.cancelapp");
//            sendBroadcast(sendIntent);
        } catch (IllegalArgumentException e) {

        }
    }

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent arg1) {
            if (arg1.getAction().equalsIgnoreCase("df.scanservice.result")) {
                String codes = arg1.getStringExtra("result");
                codes.trim();
                if (!codes.equals("")) {
                    if (codes.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_PTSM_RULE))) {
                        Bundle bundle = new Bundle();
                        bundle.putString("source", AppConfig.SEARCH);
                        bundle.putString("id", codes);
                        bundle.putString("type", AppConfig.INJECTION);
                        showActivity(aty, Act_DocAdvice.class, bundle);
                    }
                    else
                    if (codes.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_BYJ_RULE)))
//                    if (result.length() == 14)
                    {
                        Bundle bundle = new Bundle();
                        bundle.putString("source", AppConfig.SEARCH);
                        bundle.putString("id", codes);
                        bundle.putString("type", AppConfig.DISPENSING);
                        showActivity(aty, Act_DocAdvice.class, bundle);
                    } else if (codes.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_CX_RULE))) {
                        code = codes;
                        presenter.collect(PreferenceHelper.readString(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO),code,
                                PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
                    } else {
                        Toast.makeText(aty, "条码无效!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    };
}
